<?php

namespace Home\Controller;

use Home\Controller\BaseController;

vendor('aliyun.autoload');

class PublicController extends BaseController {

    public function _initialize() {
        
    }

    //用户登录
    public function login() {
        $strPhone = I("user_phone");
        $strPassword = I("password");
        $where = [];
        empty($strPhone) && $this->error("请输入手机号");
        empty($strPassword) && $this->error("请输入密码");
        $userInfo = M('user')->where(['user_phone' => $strPhone, 'password' => md5($strPassword)])->find();
        if (!$userInfo) {
            $this->error('账号或密码错误');
        }
        $this->success("登录成功", $userInfo);
    }

    //注册
    public function register() {
        $strPhone = $this->getParam('user_phone', '', 'string', TRUE, 'user_phone必须');

        $this->_authSign($strPhone);
        $strPassword = I("password");
        
        !empty($strPassword) && $data['password'] = md5($strPassword);
        !empty($strPhone) && $data['nickname'] = substr_replace($strPhone, '****', 3, 4);
        !empty($_POST['city']) && $data['city'] = $this->getParam('city');
        !empty($_POST['lat']) && $data['lat'] = I('lat');
        !empty($_POST['lon']) && $data['lon'] = I('lon');
        
        $userInfo = M('user')->where(['user_phone' => $strPhone])->find();
        if(!empty($userInfo)){
            M('user')->where(['user_phone' => $strPhone])->save($data);
        }else{
            $data['user_phone'] = $strPhone;
            $user_id = M('user')->add($data);
        }
        
        $userInfo = M('user')->where(['user_phone' => $strPhone])->find();
        if ($userInfo) {
            $this->success("操作成功", $userInfo);
        }else {
            $this->error("操作失败");
        }
    }

    //找回密码
    public function resetPwd() {
        $strPhone = I("user_phone");
        $strPassword = I("password");
        $res = M('user')->where(['user_phone' => $strPhone])->save(['password' => md5($strPassword)]);
        if ($res) {
            $this->success("修改成功");
        } else {
            $this->error("修改失败");
        }
    }

    //用户反馈
    public function feedback() {
        $data['contact_phone'] = $this->getParam('contact_phone', '', 'string', TRUE, '请填写手机号');
        $data['content'] = $this->getParam('content', '', 'string');
        $res = M('feedback')->add($data);
        if ($res) {
            $this->success("操作成功");
        } else {
            $this->error("操作失败");
        }
    }

//    //版本
//    public function checkVersion(){
//        $platform = $this->getParam('platform', 0, 'int+',TRUE);
//        switch ($platform) {
//            case '1':
//                $config_key = 'app_version_user';
//                break;
//            case '2':
//                $config_key = 'app_version_business';
//                break;
//            default:
//                $config_key = '0';
//                break;
//        }
//        
//        $configInfo = M('config')->where(['config_key'=>$config_key])->find();
//        $this->returnList($configInfo['config_value']);
//    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //验证码发送
    public function sendCode() {
        $strPhone = I('phone');
        empty($strPhone) && $this->error("请输入手机号");

        $objUser = M('CompanyUser');
        $userInfo = $objUser->where(array('company_user_phone' => $strPhone))->find();

        //验证手机号是否存在
        if (!empty($userInfo)) {
            if ($userInfo['status'] == 1) {
                $this->error("您的账号已被禁用，请联系管理员");
                return;
            }
        }

        $strCode = rand(1000, 9999);
        $smsRes = juheSms($strPhone, $strCode);
        if ($smsRes) {
            S($strPhone, $strCode, 3600);
            $this->success("发送成功", $strCode);
        } else {
            $this->error("发送失败");
        }
    }

    //判断字符串是否经过编码方法
    function is_base64($str) {
        /**
          if ($this->is_base64($img)) {
          $code = md5(time() + mt_rand(1, 9999));
          $s = file_put_contents('./Uploads/Picture/' . $code . '.png', base64_decode($img)); //返回的是字节数
          $data['company_licence_img'] = '/Uploads/Picture/' . $code . '.png';
          }
         */
        if ($str == base64_encode(base64_decode($str))) {
            return true;
        } else {
            return false;
        }
    }

    public function uploadFile() {
        $upload = new \Think\Upload();
        $upload->maxSize = 3145728; // 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg', 'mp4'); // 设置附件上传类型
        $upload->savePath = '/Uploads/file/'; // 设置附件上传目录
        $info = $upload->uploadOne($_FILES['file']);
        $isFileType = $this->getParam('isFileType', 0, 'intval');
        if (!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        } else {// 上传成功
            $this->success("操作成功", $this->aliyun($info, 'fyc2', $isFileType));
        }
    }

    private function aliyun($info, $bucket = '', $isFileType) {
        $accessKeyId = "LTAIqHi8umsf5wfD"; //去阿里云后台获取秘钥
        $accessKeySecret = "EzLk8pvftEM9yJlnaXJfLlLCh0Mibr"; //去阿里云后台获取秘钥
        $endpoint = "oss-cn-hangzhou.aliyuncs.com"; //你的阿里云OSS地址
        $ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
        //判断bucketname是否存在，不存在就去创建
        if (!$ossClient->doesBucketExist($bucket)) {
            $ossClient->createBucket($bucket);
        }
        $object = 'image/' . date('Ymd') . '/' . $info['savename']; //想要保存文件的名称
        if ($isFileType == 1) {
            $object = 'video/' . date('Ymd') . '/' . $info['savename']; //想要保存文件的名称
        }

        $file = './Uploads' . $info['savepath'] . $info['savename']; //文件路径，必须是本地的。
        //$file = "./Uploads/Uploads/2017-07-24/5975c17ec4d9d.jpg";
        try {
            $ossClient->uploadFile($bucket, $object, $file);
            if (isunlink == true) {
                unlink($file);
            }
        } catch (OssException $e) {
            $e->getErrorMessage();
        }
        $oss = "http://fyc2.oss-cn-hangzhou.aliyuncs.com/";
        return $oss . $object;
    }

    public function reportBusiness() {
        $wid = $this->getParam('wid', 0, 'int+', TRUE, '请选择商家');
        $report_phone = I("report_phone");
        $report_name = I("report_name");
        $content = I("content");
        $arr_img = I("arr_img");
        empty($report_phone) && $this->error("请输入手机号");
        empty($content) && $this->error("请输入内容");
        $data['wid'] = $wid;
        $data['report_phone'] = $report_phone;
        $data['content'] = $content;
        $data['arr_img'] = $arr_img;
        $data['report_name'] = $report_name;
        $res = M('report')->add($data);
        if ($res) {
            $this->success("举报成功");
        } else {
            $this->error("举报失败");
        }
    }

    public function phonePersonsList() {
        $business_phones = I('business_phones');
        empty($business_phones) && $this->error('business_phones参数必须');
        $list = M('seller')->field('wid,business_phone,headpic,nickname,lat,lon,isonwork,old_address,address,detail_address,ishome,state,intro,receivenum')->where(['business_phone' => array('in', $business_phones)])->select();
        foreach ($list as &$val) {
            $val['headpic'] = subOssImgUrl($val['headpic']);
        }
        $this->returnList($list);
    }

    public function editeqcode() {
        $ios_eqcode = $this->getParam('ios_eqcode');
        $android_eqcode = $this->getParam('android_eqcode');
        if (!empty($ios_eqcode)) {
            $res = M('config')->where(['config_key' => 'ios_eqcode'])->save(['config_value' => $ios_eqcode]);
        }

        if (!empty($android_eqcode)) {
            $res = M('config')->where(['config_key' => 'android_eqcode'])->save(['config_value' => $android_eqcode]);
        }
        $this->success();
    }

    public function geteqcode() {
        $list = M('config')->where(['config_key' => array('in', ['ios_eqcode', 'android_eqcode'])])->select();
        foreach ($list as $val) {
            if ($val['config_key'] == "ios_eqcode") {
                $arr['ios_eqcode'] = $val['config_value'];
            }
            if ($val['config_key'] == "android_eqcode") {
                $arr['android_eqcode'] = $val['config_value'];
            }
        }
        $this->returnList($arr);
    }

    //检查版本更新
    public function checkVersion() {
        $app_sys = $this->getParam('app_sys', 0, 'int+', TRUE, '终端系统类型必须');
        if ($app_sys == 1) {
            //安卓
            $app_sys_code = "app_version_android";
        } elseif ($app_sys == 2) {
            $app_sys_code = "app_version_ios";
        }
        $data['app_sys'] = $app_sys;
        $data['app_version'] = $this->getParam('app_version', '', 'string', TRUE, '版本号必须');
        $data['downloadurl'] = $this->getParam('downloadurl', '', 'string', TRUE, '下载地址必须');
        $data['description'] = $this->getParam('description', '', 'string');
        $data['sversion'] = $this->getParam('sversion', '', 'string');
        $data['ssversion'] = $this->getParam('ssversion', '', 'string');
        $data['isforce'] = $this->getParam('isforce');
        $res = M('config')->where(['config_key' => $app_sys_code])->save(['config_value' => json_encode($data)]);
        $this->success("设置成功");
    }

    //获取版本
    public function getVersion() {
        $app_sys = $this->getParam('app_sys', 0, 'int+', TRUE, '终端系统类型必须');
        if ($app_sys == 1) {
            //安卓
            $app_sys_code = "app_version_android";
        } elseif ($app_sys == 2) {
            $app_sys_code = "app_version_ios";
        }
        $info = M('config')->where(['config_key' => $app_sys_code])->getField('config_value');
        $this->returnList(json_decode($info, TRUE));
    }

    

    public function setlogin() {
        $this->_authSign2();
        $did = $this->getParam('did', '', 'string', TRUE, 'did必须');
        $state = $this->getParam('state', 0, 'int+', TRUE, 'state必须');
        $didInfo = M("did")->where(array('did' => $did))->find();
        if (empty($didInfo)) {
            $data['did'] = $did;
            $data['state'] = $state;
            M("did")->add($data);
        } else {
            $data['state'] = $state;
            M("did")->where(array('did' => $did))->save($data);
        }
        $this->success();
    }

    public function getlogin() {
        $this->_authSign2();
        $did = $this->getParam('did', '', 'string', TRUE, 'did必须');
        $state = M("did")->where(array('did' => $did))->getField("state");
        $this->returnList(['state'=>$state]);
    }
    
    private function _authSign2() {
        
        $sign = $this->getParam('sign', '', 'string', TRUE, 'sign必须');
        $did = $this->getParam('did', '', 'string', TRUE, 'did必须');
        if(md5(C('APP_AUTH_KEY').$did) != $sign){
            $this->error("非法操作");
        }
    }
    
    public function setEvalutionTags() {
        $tags = $this->getParam('tags', '', 'string', TRUE, 'tags必须');
        M("tags")->where(['tag_id' => 1])->save(['tag_value' => $tags]);
        $this->success();
        
    }
    
    public function getEvalutionTags() {
        $tagValue = M("tags")->where(['tag_id' => 1])->getField("tag_value");
        $this->returnList(explode(",", $tagValue));
    }
    
    public function setCitys() {
        $citys = $this->getParam('citys', '', 'string', TRUE, 'citys必须');
        M("city")->where(['id' => 1])->save(['value' => $citys]);
        $this->success();
        
    }
    
    public function getCitys() {
        $value = M("city")->where(['id' => 1])->getField("value");
        $this->returnList(explode(",", $value));
    }
    
    public function setshenhe(){
        $shenhestate = $this->getParam('shenhestate', 0, 'int+', TRUE, '审核状态参数必须');
        $res = M('config')->where(['config_key' => 'shenhestate'])->save(['config_value' => $shenhestate]);
        $this->success();
    }
    
    public function getshenhe(){
        $info = M('config')->where(['config_key' => 'shenhestate'])->getField('config_value');
        $this->returnList($info);
    }
    
    //获取用户列表
    public function userPersonsList() {
        $user_phones = $this->getParam('user_phones', '', 'string', TRUE, 'user_phones必须');
        
        $list = M('user')->where(['user_phone' => ['in', $user_phones]])->select();
        $this->returnList($list);
    }
    
    //用户编辑
    public function updateUserinfo() {
        $user_phone = $this->getParam('user_phone', '', 'string', TRUE, 'user_phone必须');
        $nickname = $this->getParam('nickname');
        !empty($nickname) && $data['nickname'] = $nickname;
        !empty($_POST['headpic']) && $data['headpic'] = $_POST['headpic'];
        !empty($_POST['zan']) && $data['zan'] = $_POST['zan'];
        !empty($_POST['cai']) && $data['cai'] = $_POST['cai'];
        !empty($_POST['remark']) && $data['remark'] = $_POST['remark'];
        
        
//        $res = M('user')->where(['user_id' => $this->user_id])->save($data);
        $res = M('user')->where(['user_phone' => $user_phone])->save($data);
        $this->success('修改成功');
    }
    
}
